<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<c:set var="ctx" value="${pageContext.request.contextPath}" />

<!doctype html>
<html>
<head>
    <title>数据字典</title>
    <jsp:include page="/common/init.jsp"></jsp:include>
    <link href="${ctx}/assets/zTree/css/zTreeStyle/zTreeStyle.css" type="text/css" rel="stylesheet" />
    <script src="${ctx}/assets/zTree/js/jquery.ztree.all.js" type="text/javascript" charset="UTF-8"></script>
    <script type="text/javascript">
        var path='<%=request.getContextPath() %>';
        var selectedData;
        var deptTreeSet;
        $(function() {
            var deptTree = null;
            var deptTreeNodes = null;
            var selDeptID = "";
            var deptTreeSet;
            // -- 用户查询  --
//            var userTable = $("#userList").DataTable({
//                //"sDom" : "<'row-fluid'f>t<'row-fluid'<'span4'i><'span2'r><'span8'<'pull-right'p>>>",
//                bDestroy: true,
//                bFilter: false,
//                bProcessing: true,
//                bPaginate: true,
//                bAutoWidth: true,
//                bServerSide: true,
//                bStateSave:false,
//                bSort:false,
//                bLengthChange:false,
//                sScrollY:420,
//                sScrollX: "100%",
//                sScrollXInner: "150%",
//                bScrollCollapse:true,
//                sServerMethod: "POST",
//                iDisplayLength: 10,
//                iDisplayStart: 0,
//                fnDrawCallback : addSelectListener,
//                sAjaxSource : path + "/user/getUserList",//获取列表数据url,
//                "oLanguage" : {
//                    "sSearch" : "检索："
//                },
//                aoColumns: [
//                    {'mDataProp':'LOGIN_ID' , 'sTitle' : '登录名','sWidth' : '10%','sClass' : 'center'},
//                    {'mDataProp':'USER_NAME' ,'sTitle' : '用户','sWidth' : '10%','sClass' : 'center'},
//                    {'mDataProp':'DEPT_NAME' ,'sTitle' : '部门','sWidth' : '10%','sClass' : 'center'}
//                ],
//                aoColumnDefs: [
//                    {
//                        aTargets: ["_all"],
//                        mRender: function (data, type, row) {
//                            var subData = data;
//                            if (data instanceof Object) {
//                                try {
//                                    return new Date(data.time).format("yyyy-MM-dd");
//                                } catch (e) {
//                                    subData = data;
//                                }
//                            }
//                            return subData;
//
//                        }
//                    }
//                ],
//                fnServerParams : function(aoData) {
//                    aoData.push({
//                        "name" : "dept_id",
//                        "value" : selDeptID
//                    });
//                }
//            });
            // -- 部门组织架构树  --
            try {

                 deptTreeSet = {
                     async: {
                         enable: true,
                         autoParam: ['id=selDeptID'],
                         contentType: 'application/x-www-form-urlencoded',
                         url: path + "/dict/getChildById",
                         dataType: 'json',
                         type: 'post'
                     },
                    data : {
                        key : {
                            name : "dictValue" // 节点名称的属性
                        },
                        simpleData : {
                            enable : true, // 使用简单数据模型（array），但请注意simpleData内的参数（idKey，pIdKey，rootPId）满足父子关系
                            idKey : "id",
                            pIdKey : "dictParentId",
                            rootPId : "ROOT",
                            code : "code",
                            parentCode : "parentCode"
                        }
                    },
                    callback : {
                        onClick : function(e, treeId, treeNode) { // 节点点击事件
                            /* if(!treeNode.isParent){ // 叶子节点
                                deptTreeNodes = treeNode;
                                selDeptCD = "'" +treeNode.DEPT_CD+ "'";
                                // 刷新用户列表
                                $('#userList').dataTable().fnReloadAjax();
                            }else{				// 非叶子节点
                                var leafDeptCDArray = [];
                                recursionSearch(treeNode,leafDeptCDArray);
                                selDeptCD = leafDeptCDArray.toString();
                            } */
                            selDeptID = treeNode.id;
                            // 刷新用户列表
//                            userTable.ajax.reload();

                            var users=[{name:"张三", age:'21', birth:'1994-12-12'}];
                            var params = {};
                            params.selDeptID = selDeptID;
                            $('#dictParentId').val(selDeptID);

                            $.ajax(
                                {
                                    async : false,
                                    cache : false,
                                    type : 'post',
                                    data:   params,
                                  /*  contentType: 'application/x-wwww-form-urlencoded;charset=UTF-8',*/
                                    url : path + "/dict/getByDictId",
                                    success : function(data) {
//                                        console.log(data);
                                        $('#parentCode').val(data.sysDict.code);
                                        $('#code').val(data.sysDict.code);
                                        $('#dictVal').val(data.sysDict.dictValue);
                                        $('#dictDes').val(data.sysDict.dictDesc);
                                        $('#dictId').val(data.sysDict.id);
                                        $('#dictSort').val(data.sysDict.dictSort);
                                        $('#otherValue').val(data.sysDict.otherValue);
                                        $('#optUser').val(data.sysDict.user.userName);

                                        $('#dictAvailable').val(data.sysDict.dictAvailable?'是' : '否');


                                        var date = new Date(data.sysDict.optDate);
                                        Y = date.getFullYear()+'/';
                                        M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : data.getMonth()+1)+'/';
                                        D=date.getDate()+ ' ';
                                        h = date.getHours()+':';
                                        m = date.getMinutes() +':';
                                        s = date.getSeconds();

                                        if(
                                            data.sysDict.user == null
                                        ){
                                            $('#dictPerson').html("");
                                        }else {
                                            $('#dictPerson').html(data.sysDict.user.userName);
                                        }
                                        if(data.sysDict.optDate == null || data.sysDict.optDate == "") {
                                                $('#dictDate').html("");
                                        }
                                        else{
                                                $('#dictDate').val(Y+M+D+h+m+s);
                                        }


                                    },
                                    error: function(err) {
                                    }
                                }
                            )
                        }
                    }
                };

                $.ajax({
                    async : false,
                    cache : false,
                    type : 'POST',
                    dataType : "json",
                    url : path + "/dict/list",
                    error : function(xhr, textStatus, exception) {
                        ////notyError  ('部门数据加载失败!' + xhr.responseText);
                    },
                    success : function(data) {
                        deptTree = $.fn.zTree.init($("#deptTree"), deptTreeSet,
                            data);
                        // 展开根节点
                        deptTree.expandNode(deptTree.getNodeByParam("PARENTID",
                            "-1", null), true, false, false);
                    }
                });
            } catch (e) {
                //notyError (e);
            }

            $("#insertDict").click(function () {

                var dictId = $('#dictId').val();
                if(dictId == "") {
                   notyInfo("请选择父级字典");
                }
                else {
                     $('#insertDictModel').modal('show');
                }
//                $.ajax({
//                    async : true,
//                    cache : false,
//                    data: {'dictId':dictId},
//                    type : 'post',
//                    dataType:'json',
//                    url : path + "/dict/toInsert",
//                    success: function (data) {
//                    }
//                });
            });

            $("#updateDict").click(function () {
                var valid = $("#dictDataForm").validationEngine('validate');
                if (!valid)
                    return;
                if($('#dictVal').val() == null || $('#dictVal').val() == '') {
                    notyWarning("请填写字典名称");
                }else

                if($('#dictSort').val() == null || $('#dictSort').val() == '') {
                    notyWarning("数据字典顺序不能为空");
                }else {

                    $.ajax({
                        type: 'POST',
                        data: $('#dictDataForm').serialize(),
                        url: path + "/dict/update",
                        success: function (data) {
                            if (data.result == true) {
                                notySuccess("更新成功");
                                $.ajax({
                                    async: false,
                                    cache: false,
                                    type: 'POST',
                                    dataType: "json",
                                    url: path + "/dict/list",
                                    error: function (xhr, textStatus, exception) {
                                        ////notyError  ('部门数据加载失败!' + xhr.responseText);
                                    },
                                    success: function (data) {
//                                        deptTree = $.fn.zTree.init($("#deptTree"), deptTreeSet,
//                                            data);
                                        // 展开根节点
//                                        deptTree.expandNode(deptTree.getNodeByParam("PARENTID",
//                                            "-1", null), true, false, false);
                                        var $nodes = deptTree.getSelectedNodes();
                                        deptTree.reAsyncChildNodes($nodes[0],'refresh',false)
                                    }
                                });
                            }
                            else {
                                notyError("更新失败");
                            }

                        }
                    })
                }
            });

            $('#saveDict_btn').click(function () {
                var valid = $("#insertDictForm").validationEngine("validate");
                if (!valid)
                    return;

                /*if($('#dict_code').val() == null || $('#dict_code').val() == '') {
                    notyWarning("请填写字典CODE");
                }else*/

                if($('#dict_value').val() == null || $('#dict_value').val() == '') {
                    notyWarning("请填写字典名称");
                }else

                if($('#dict_sort').val() == null || $('#dict_sort').val() == '') {
                    notyWarning("请填写字典顺序值");
                }
                else {
                    $.ajax({
                        url: '${ctx}/dict/insertDict',
                        type: 'POST',
                        data: $('#insertDictForm').serialize(),
                        success : function (data) {
                            if (data.result == true) {
                                notySuccess("添加成功");
                                $('#insertDictModel').modal('hide');
                                $.ajax({
                                    async : false,
                                    cache : false,
                                    type : 'POST',
                                    dataType : "json",
                                    url : path + "/dict/list",
                                    error : function(xhr, textStatus, exception) {
                                        ////notyError  ('部门数据加载失败!' + xhr.responseText);
                                    },
                                    success : function(data) {
//                                        var $nodes = deptTree.getSelectedNodes();
//                                        deptTree = $.fn.zTree.init($("#deptTree"), deptTreeSet,
//                                            data);
//                                        // 展开节点
//                                        deptTree.expandNode($nodes[0], true, false, false);
                                        var $nodes = deptTree.getSelectedNodes();
                                        deptTree.reAsyncChildNodes($nodes[0],'refresh',false)
                                    }
                                });
                            }
                            else {
                                notyError(data.message);
                            }
                        }
                    });
                }
                    <%--$.ajax({--%>
                                <%--url: '${ctx}/dict/insertDict',--%>
                                <%--type: 'POST',--%>
                                <%--data: $('#insertDictForm').serialize(),--%>
                                <%--success : function (data) {--%>
                                    <%--if (data.result == true) {--%>
                                        <%--notySuccess("添加成功");--%>
                                    <%--}--%>
                                    <%--else {--%>
                                        <%--notyError("添加失败");--%>
                                    <%--}--%>
                                <%--}--%>
                    <%--});--%>
                            <%--&lt;%&ndash;$.ajax({&ndash;%&gt;--%>
                                <%--async : false,--%>
                                <%--cache : false,--%>
                                <%--type : 'POST',--%>
                                <%--dataType : "json",--%>
                                <%--url : path + "/dict/list",--%>
                                <%--error : function(xhr, textStatus, exception) {--%>
                                    <%--////notyError  ('部门数据加载失败!' + xhr.responseText);--%>
                                <%--},--%>
                                <%--success : function(data) {--%>
                                    <%--deptTree = $.fn.zTree.init($("#deptTree"), deptTreeSet,--%>
                                        <%--data);--%>
                                    <%--// 展开根节点--%>
                                    <%--deptTree.expandNode(deptTree.getNodeByParam("PARENTID",--%>
                                        <%--"-1", null), true, false, false);--%>
                                <%--}--%>
                            <%--});--%>

            });



        });

//        function addSelectListener() {
//            //找到列表中的数据行
//            var rows = $("#userList tr");
//            $.each(rows, function(index, row) {
//                if (index > 0) {
//                    $(row).click(
//                        function() {
//                            selectedData = $('#userList').dataTable().fnGetData(this);
//                            $("#choicedUserName").html("<strong>"+selectedData.USER_NAME+"</strong> ["+selectedData.LOGIN_ID+"]");
//                            $(row).addClass("info");
//                            $(row).siblings().removeClass("info");
//                        });
//                }
//            });
//        }

    </script>
</head>
<body>
<div class="bg-white item_title">
    数据字典
</div>
<div class="bg-white">
    <div class="row">
        <div class="col-xs-3">
            <div class="box">
                <div class="box-header">
                    <div class="row">
                        <div class="col-xs-7">
                            <span><h4><i class="fa fa-users"></i> 数据字典树</h4></span>
                        </div>
                        <div class="col-xs-5">
                            <input class="btn btn-md btn-primary" type="button" id = "insertDict" value="增加">
                        </div>
                    </div>


                </div>
                <br>
                <div class="box-content">
                    <ul id="deptTree" class="ztree"></ul>
                </div>
            </div>
        </div>
        <div class="col-xs-9">
            <div class="box">
                <div class="box-header">
                    <span><h4><i class="fa fa-building"></i> 字典编辑</h4></span>
                </div>
                <br>
                <form id="dictDataForm">
                    <div class="box-content form_search form_table container-fluid">
                            <div class="row form-group">
                                <%--<div class="col-xs-4">
                                    <div class="form-item wide2">
                                        <label> *字典编码：</label>
                                        <input class="form-control wide" type="text" readonly id="code" name="code" maxlength="20" placeholder="长度不能超过20">
                                    </div>
                                </div>--%>

                                <div class="col-xs-4">
                                    <div class="form-item wide2">
                                        <label> *字典名称：</label>
                                        <input class="form-control wide" type="text" id="dictVal" name="dictValue" maxlength="20" placeholder="长度不能超过20">
                                    </div>
                                </div>
                                <div class="col-xs-4">
                                    <div class="form-item wide2">
                                        <label> 字典描述：</label>
                                        <input class="form-control wide" type="text" id="dictDes" name="dictDesc" maxlength="100" placeholder="长度不能超过100">
                                    </div>
                                </div>

                                <div class="col-xs-4">
                                    <div class="form-item wide2">
                                        <label>*字典顺序：</label>
                                        <input class="form-control wide" type="text" id="dictSort" name="dictSort">
                                    </div>
                                </div>
                            </div>

                            <div class="row form-group">

                                <div class="col-xs-4">
                                    <div class="form-item wide2">
                                        <label>创建人：</label>
                                        <input class="form-control wide" type="text" id="optUser" readonly>
                                    </div>
                                </div>
                                <div class="col-xs-4">
                                    <div class="form-item wide2">
                                        <label>创建时间：</label>
                                        <input id="dictDate" readonly class="form-control wide" >
                                    </div>
                                </div>

                                <div class="col-xs-4">
                                    <div class="form-item wide2">
                                        <label>其它值：</label>
                                        <input class="form-control wide validate[custom[number]]" type="text" id="otherValue" name="otherValue">
                                    </div>
                                </div>
                            </div>


                            <input type="text" id ="dictId" hidden="hidden" name="id">

                            <div class="btns_form mt15 mb15">
                                <input class="btn btn-md btn-info" type="button" id="updateDict" value="修改后请保存"/>

                            </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<%--增加数据字典的model--%>
<div id="insertDictModel" class="modal fade" data-backdrop="static">
    <form id="insertDictForm" name="wfRoleForm" class="form-horizontal opend_modal">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <a data-dismiss="modal"><i class="fa fa-close"></i> </a>
                    <b>增加数据字典</b>
                </div>
                <div class="modal-body container-fluid">
                    <div class="single_line_form">
                        <%--//父级的ID--%>
                           <input id="dictParentId"  name="dictParentId" hidden>
                            <input id ="parentCode"  name="parentCode"   hidden>
                        <%--<div class="form-group">
                            <label class="col-xs-3 control-label"><span class="required"> * </span>字典编码:</label>
                            <div class="col-xs-9">
                                <input id="dict_code" name="code" type="text" class="form-control" />
                            </div>
                        </div>--%>
                        <div class="form-group">
                            <label class="col-xs-3 control-label"><span class="required"> * </span>字典名称:</label>
                            <div class="col-xs-9">
                                <input id="dict_value" name="dictValue" type="text" class="form-control" />
                            </div>
                        </div>

                        <div class="form-group">
                            <label class="col-xs-3 control-label">字典描述:</label>
                            <div class="col-xs-9">
                                <input id="dict_desc" name="dictDesc" type="text" class="form-control" />
                            </div>
                        </div>

                        <div class="form-group">
                            <label class="col-xs-3 control-label"><span class="required"> * </span>字典顺序:</label>
                            <div class="col-xs-9">
                                <input id="dict_sort" name="dictSort" type="text" class="form-control" />
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-xs-3 control-label">其它值:</label>
                            <div class="col-xs-9">
                                <input id="other_value" name="otherValue" type="text" class="form-control validate[custom[number]]" />
                            </div>
                        </div>
                        <%--<div class="control-group">--%>
                            <%--<label class="yf-control-label">排序：</label>--%>
                            <%--<div class="yf-controls">--%>
                                <%--<input id="ROLE_ORDER" name="ROLE_ORDER" type="text" class="form-control" />--%>
                                <%--<div class="help-block"></div>--%>
                            <%--</div>--%>
                        <%--</div>--%>

                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-md btn-success" id="saveDict_btn">保存</button>
                    <%--<button type="reset" class="btn btn-md purple" style="display: none">重置</button>--%>
                    &nbsp;
                    <button class="btn btn-md btn-default" data-dismiss="modal" aria-hidden="true"><i class="fa fa-close"></i>关闭</button>
                </div>
            </div>
        </div>
    </form>
</div>


</body>
</html>
